import React, { useState, useEffect, useCallback } from 'react';
import {
  Button,
  Form,
  Input,
  DatePicker,
  Select,
  Radio,
  message,
  Space,
  InputNumber,
  Tooltip,
} from 'antd';
import { ExclamationCircleOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import SelectIpa from './SelectIpa';
import FileScanner from './FileScanner';
import SelectTemplate from './SelectTemplate';
import { debounce } from 'lodash';
import moment from 'moment';
import {
  massSendInfo,
  judgeIndustryCanEdit,
  getSignatureList,
  jsonDoEncrypt,
} from 'admin/servers/servers';
import { flatTryCatch } from '../../../../servers/http';
import { extract } from './utils';
import './index.scss';

const timeFormat = 'YYYY-MM-DD HH:mm:ss';
const { TextArea } = Input;
const { Option } = Select;

const MassSMS: React.FC = () => {
  const [form] = Form.useForm();

  /**
   * 接收 通讯录&FileScanner
   * @param data 手机号码列表
   */
  const handleAcceptPhone = (data: string[]) => {
    // 以回车分隔
    let newText = data.join('\n');
    // 获取原有的; 初次或空串，不加到最前
    const currentText = form.getFieldValue('phone');
    if (currentText != undefined && currentText !== '') {
      newText = currentText + '\n' + newText;
    }
    form.setFieldsValue({ phone: newText });
    // 验证一下
    form.validateFields(['phone']);
  };

  // 号码验证
  const validatePhoneNumbers = (_, value) => {
    if (!value) {
      return Promise.reject(new Error('请输入号码列表'));
    }

    const phoneNumbers = value.split('\n').map(phone => phone.trim());
    const invalidPhones = phoneNumbers.filter(phone => !/^1[3-9]\d{9}$/.test(phone));

    if (invalidPhones.length > 0) {
      return Promise.reject(new Error('所有手机号必须是有效的手机号'));
    }

    return Promise.resolve();
  };

  /** 短信内容 */
  // 是否有模板可编辑
  const [canEdit, setCanEdit] = useState(false);
  const fetchCanEdit = useCallback(async () => {
    const {
      response: { data },
      error,
    } = await flatTryCatch(judgeIndustryCanEdit());
    if (error) return;
    setCanEdit(data.templateEdit);
  }, []);
  useEffect(() => {
    fetchCanEdit();
  }, [fetchCanEdit]);

  // 切换自填、模板
  const [isDisMsg, setIsDisMsg] = useState(true); // true:不可编辑 | false:可编辑
  const onTemplateRadioChange = e => {
    const value = e.target.value;
    setIsDisMsg(value === 2);
    // 从可编辑切换到不可编辑，读取下内容进行重新解析
    if (value === 2) {
      const msg = form.getFieldValue('msg');
      setTempFields(extract(msg));
    }
  };

  // 接收选择的模板
  const [tempFields, setTempFields] = useState({}); // 提取出来的模板字段
  const [templateId, setTemplateId] = useState(); // 提取出来的模板id
  const handleAcceptTemplate = pitchTemplate => {
    form.setFieldsValue({
      msg: pitchTemplate.content,
    });
    setTemplateId(pitchTemplate.id);
    setTempFields(extract(pitchTemplate.content));
  };

  // 模板参数输入
  const handleChangeTempFields = e => {
    const { name, value } = e.target;
    setTempFields({
      ...tempFields,
      [name]: value,
    });
  };

  /** 签名列表 */
  const [signatureList, setSignatureList] = useState([]);
  const fetchSignatureList = useCallback(async () => {
    const {
      response: { list = [] },
      error,
    } = await flatTryCatch(getSignatureList());
    if (error) return;
    setSignatureList(list);
  }, []);
  useEffect(() => {
    fetchSignatureList();
  }, [fetchSignatureList]);

  /** 显隐时间 */
  const [isShowTime, setIsShowTime] = useState(false);
  const onRadioChange = e => {
    const value = e.target.value;
    setIsShowTime(value === 2);
  };

  /** 显隐次数间隔 */
  const [isShowInterval, setIsShowInterval] = useState(false);
  const onFreqChange = (value: number) => {
    setIsShowInterval(value > 1);
  };

  /**操作: 发送 */
  const [sendLoading, setSendLoading] = useState(false);
  const handleFinish = debounce((values: any) => {
    form
      .validateFields()
      .then(async () => {
        const params = values;
        if (values.startTime) {
          params.startTime = moment(values.startTime).format(timeFormat);
          if (new Date(values.startTime).getTime() <= new Date().getTime()) {
            message.warning('定时发送时间必须大于当前时间');
            return;
          }
        }
        if (values.phone) {
          values.phone = values.phone.split('\n').join(',');
        }
        if (isDisMsg) {
          params.templateParam = tempFields;
          params.templateId = templateId;
        }
        const json = jsonDoEncrypt(params);
        setSendLoading(true);
        const { response, error } = await flatTryCatch(massSendInfo({ json }));
        setSendLoading(false);
        if (error) return;
        if (response.code === 0) {
          message.success('提交成功');
          handleReset();
          // 重置模板额外信息
          setIsDisMsg(true);
          setTempFields({});
        }
      })
      .catch(() => {});
  }, 500);

  /**操作: 重置 */
  const handleReset = () => {
    form.resetFields();
  };

  /** 往前时间不能选 */

  // 禁用当前时间之前的日期
  const disabledDate = current => {
    return current && current < moment().startOf('day');
  };

  // 禁用当前时间之前的时分秒
  // const disabledTime = current => {
  //   const now = moment();
  //   const hours = now.hour();
  //   const minutes = now.minute();
  //   const seconds = now.second();

  //   if (current && moment(current).isSame(now, 'day')) {
  //     return {
  //       disabledHours: () => Array.from({ length: hours }, (_, i) => i),
  //       disabledMinutes: () => Array.from({ length: minutes }, (_, i) => i),
  //       disabledSeconds: () => Array.from({ length: seconds }, (_, i) => i),
  //     };
  //   }
  //   return {
  //     disabledHours: () => [],
  //     disabledMinutes: () => [],
  //     disabledSeconds: () => [],
  //   };
  // };

  /** 实时监听 */
  const [signName, setSignName] = useState<string>(''); // 用于实时显示的签名
  const [msgContent, setMsgContent] = useState<string>(''); // 用于实时显示的短信内容
  const [msgBar, setMsgBar] = useState<number>(0); // 用于实时显示的短信的条数

  // 根据短信内容计算条数 内容+签名
  const calculateMsgCount = (msg: string, name: string) => {
    const len = (msg?.length || 0) + (name?.length || 0);
    if (len === 0) return 0;
    if (len <= 70) return 1;
    return Math.ceil(len / 67);
  };

  const handleFormValuesChange = (changedValues: { [key: string]: any }, allValues: any) => {
    if ('singId' in changedValues) {
      const matchSign = signatureList.find(({ id }) => changedValues.singId === id) ?? {
        content: '',
      };
      setSignName(matchSign.content);
      setMsgBar(calculateMsgCount(msgContent, matchSign.content));
    }
    if ('msg' in changedValues) {
      setMsgContent(changedValues.msg);
      setMsgBar(calculateMsgCount(changedValues.msg, signName));
    }
  };

  return (
    <div className="page-main-container mass-container">
      <div className="mass-left">
        <div className="marked-words">
          <ExclamationCircleOutlined />{' '}
          提示：发送短信之前确认当前发送账号已配置相应发送资源；支持手动输入手机号码，同时也支持通过xls、xlsx、csv或et文件批量导入手机号码；发送短信之前检查短信内容前后是否带有空格防止多条计费；支持定时短信发送；
        </div>
        <Form
          form={form}
          onFinish={handleFinish}
          initialValues={{ modelType: 2 }}
          onValuesChange={handleFormValuesChange}
        >
          <Form.Item
            label="任务名称"
            name="name"
            rules={[{ required: true, message: '请输入任务名称' }]}
          >
            <Input placeholder="请输入任务名称" maxLength={50} />
          </Form.Item>

          <div className="flex-layout">
            <SelectIpa onPhoneFromChild={handleAcceptPhone} />
            <FileScanner onPhoneFromChild={handleAcceptPhone} />
          </div>
          <Form.Item
            label="号码列表"
            name="phone"
            rules={[{ required: true, message: '' }, { validator: validatePhoneNumbers }]}
            // validateTrigger={['onBlur', 'onChange']}
          >
            <TextArea placeholder="请输入号码列表" rows={6} />
          </Form.Item>

          <Form.Item label="签名" name="singId" rules={[{ required: true, message: '请选择签名' }]}>
            <Select placeholder="请选择签名" allowClear>
              {signatureList.map(sign => (
                <Option value={sign.id} key={sign.id}>
                  {sign.content}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <div className="flex-layout">
            <Form.Item name="modelType">
              <Radio.Group onChange={onTemplateRadioChange}>
                {canEdit && <Radio value={1}>短信自编辑</Radio>}
                <Radio value={2}>选择模板</Radio>
              </Radio.Group>
            </Form.Item>
            <SelectTemplate onTemplateFromChild={handleAcceptTemplate} />
          </div>
          <div className="note-content">
            <Form.Item
              label="短信内容"
              name="msg"
              rules={[{ required: true, message: '请输入短信内容' }]}
            >
              <TextArea
                disabled={isDisMsg}
                placeholder="请输入短信内容"
                // showCount
                rows={4}
                maxLength={500}
              />
            </Form.Item>
            <div className="note-tip">
              共{msgContent.length + signName.length}字（包含签名字数），<b>{msgBar}</b>条短信{' '}
              <Tooltip
                placement="top"
                title={
                  '短信字数<=70个字，按照70个字一条短信计算。中文英文符号统一计算为一个字符。 短信字数>70个字，占用3个字符作为分条字符，按照67个字记为一条短信计算'
                }
              >
                <QuestionCircleOutlined />
              </Tooltip>
            </div>
          </div>
          {isDisMsg && (
            <div className="temp-fields">
              {Object.keys(tempFields).map(filed => (
                <div key={filed}>
                  {filed}
                  <Input
                    name={filed}
                    placeholder="请输入参数值"
                    value={tempFields[filed]}
                    onChange={handleChangeTempFields}
                  />
                </div>
              ))}
            </div>
          )}

          <div className="flex-layout">
            <Form.Item label="发送方式" name="timeType">
              <Radio.Group onChange={onRadioChange}>
                <Radio value={1}>立即发送</Radio>
                <Radio value={2}>定时发送</Radio>
              </Radio.Group>
            </Form.Item>
            {isShowTime && (
              <Form.Item
                name="startTime"
                rules={[{ required: true, message: '请选择定时发送时间' }]}
              >
                <DatePicker
                  showTime
                  placeholder="请选择定时发送时间"
                  disabledDate={disabledDate}
                  // disabledTime={disabledTime}
                />
              </Form.Item>
            )}
          </div>

          {/* <div className="flex-layout">
          <Form.Item
            label="发送次数"
            name="sendFreq"
            rules={[{ required: true, message: '请输入发送次数' }]}
          >
            <InputNumber min={1} onChange={onFreqChange} />
          </Form.Item>
          {isShowInterval && (
            <Form.Item
              label="间隔"
              name="interval"
              rules={[{ required: true, message: '请选择间隔' }]}
            >
              <Radio.Group>
                <Radio value={1}>半小时</Radio>
                <Radio value={2}>一小时</Radio>
                <Radio value={3}>两小时</Radio>
              </Radio.Group>
            </Form.Item>
          )}
        </div> */}

          <Form.Item>
            <Button type="primary" htmlType="submit" loading={sendLoading}>
              提交发送
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={handleReset}>
              重置
            </Button>
          </Form.Item>
        </Form>
      </div>
      <div className="mass-right">
        <div className="phone-content">
          {signName}
          {msgContent}
        </div>
        <img src="/webapp/phone.png" />
      </div>
    </div>
  );
};

export default MassSMS;
